#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/11/9 16:53
# @Author    :cjw
from selenium.webdriver import Remote, DesiredCapabilities

from use_custom_web.setting import *
from use_custom_web.base.base_browser import BaseBrowser


class Chrome(BaseBrowser):
	"""谷歌浏览器启动类"""

	start_maximized = CHROME_START_MAXIMIZED  # 浏览器最大化
	method_mark = CHROME_METHOD_MARK  # 控制浏览器启动特性是否设置
	option_mark = CHROME_OPTION_MARK  # 控制浏览器启动参数是否添加
	is_debugger = IS_DEBUGGER  # 控制是否开启复用浏览器
	experimental_option = CHROME_EXPERIMENTAL_OPTION  # 实验选项
	windows_size = CHROME_WINDOW_SIZE  # 浏览器显示尺寸

	@property
	def options(self):
		"""谷歌浏览器特有启动参数选项"""
		# 是否添加启动参数选项
		if self.option_mark:
			options = self._option()
			# 复用浏览器对应某些参数互斥，导致报错，需要特殊处理
			if self.is_debugger:
				options.debugger_address = DEBUGGER_ADDRESS
			else:
				# 添加启动参数
				options.add_argument(self.start_maximized)
				options.headless = HEADLESS
				# 添加实验参数
				for k, v in self.experimental_option.items():
					options.add_experimental_option(k, v)
			return options
		return

	@property
	def browser(self):
		"""启动谷歌浏览器，返回浏览器实例"""
		# 判断是否远程启动
		if IS_REMOTE:
			# 判断是否添加启动控制参数
			if options := self.options:
				chrome = Remote(self._command_executor, options=options,
				                desired_capabilities=DesiredCapabilities.CHROME)
			else:
				chrome = Remote(self._command_executor, desired_capabilities=DesiredCapabilities.CHROME)
		else:
			if options := self.options:
				chrome = self._browser(self._driver_path, options=options)
			else:
				chrome = self._browser(self._driver_path)

		# 浏览器启动特性是否设置
		if self.method_mark:
			chrome.implicitly_wait(self.implicit_waiting)
			chrome.set_page_load_timeout(self.page_load_time)
			chrome.set_script_timeout(self.script_timeout)
		return chrome
